# 多网卡情况下，根据前缀获取IP
import socket


def GetLocalIPByPrefix(prefix):
    """
    prefix = "192.168"
    """
    localIP = ''
    for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
        if ip.startswith(prefix):
            localIP = ip
    return localIP


def get_local_ip(ifname='eth0'):
    """
        prefix = enp2s0  or eth0
    :param ifname: 
    :return: 
    """
    import socket, fcntl, struct
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', bytes(ifname[:15], 'utf-8')))[20:24])

